package lpc

import (
	"log"
	"net"
	"os"
	"runtime"
	"strings"

	"github.com/Qingluan/Tunnel/tcp"
)

func SimpleClient(apiserver string, protocol ...string) (conn net.Conn) {
	// var conn net.Conn
	var err error
	pro := "tls"
	if protocol != nil {
		pro = protocol[0]
	}
	if strings.HasPrefix(apiserver, "/") {
		conn, err = net.Dial("unix", apiserver)
	} else {
		conn, _, err = tcp.ExpressDial(apiserver, pro, false)
	}
	if err != nil {
		log.Println("Dial error", err, apiserver)
		return
	}
	return
}

func UnixListener() (ln net.Listener, err error) {
	if runtime.GOOS != "windows" {
		if strings.HasPrefix(SOCK_FILE_PATH, "/") {
			os.Remove(SOCK_FILE_PATH)
			ln, err = net.Listen("unix", SOCK_FILE_PATH)
		} else if strings.Contains(SOCK_FILE_PATH, "\\") {
			os.Remove(SOCK_FILE_PATH)
			ln, err = net.Listen("unix", SOCK_FILE_PATH)
		}
	} else {
		ln, err = net.Listen("tcp", SOCK_FILE_PATH)
	}
	return
}

func SimpleTcpListener(protocol ...string) (ln net.Listener, err error) {
	// ln, err = net.Listen("tcp", "0.0.0.0:65531")
	pro := "tls"
	if protocol != nil {
		pro = protocol[0]
	}
	ln, err = tcp.ExpressListenWith("0.0.0.0:65531", pro, false)
	return
}

func GetAPINames() (s []string) {
	for name := range APIDB {
		s = append(s, name)
	}
	return
}

func GetAPINamesR(q string) (a string) {
	for name, v := range APIDB {
		if v.BinFilePath == q {
			return name
		}
	}
	return
}
